package com.hjy.im.server.handler;

import com.hjy.im.message.RpcResponseMessage;
import com.hjy.im.server.ChatServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    static final Logger log = LoggerFactory.getLogger(ChatServer.class);
    public static Map<Integer, Promise<Object>> promiseMap = new ConcurrentHashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        log.debug("{}", msg);
        final Promise<Object> promise = promiseMap.remove(msg.getSequenceId());//获取到请求序列号 返回并删除对应的返回结果
        if(promise != null){
            Object returnValue = msg.getReturnValue();
            Exception exceptionValue = msg.getExceptionValue();
            if (exceptionValue != null){
                promise.setFailure(exceptionValue);
            }else{
                promise.setSuccess(returnValue);
            }
        }


        System.out.println((String)msg.getReturnValue());
    }
}